import { useState } from 'react'
import * as articleService from '../services/article.service'
import * as React from 'react'
import styles from '../styles/Post.module.scss'
import { Button, Input, Menu, Layout } from 'antd'
import 'antd/dist/antd.css'
import toast from '../components/Toast'
import * as userService from '../services/user.service'
import { Editor } from '@bytemd/react'
import gfm from '@bytemd/plugin-gfm'
import highlight from '@bytemd/plugin-highlight'
import zhHans from 'bytemd/lib/locales/zh_Hans.json'
import 'highlight.js/styles/vs.css'
import 'bytemd/dist/index.min.css'
import Header from '../components/header'
import { GetServerSideProps } from 'next'
import { IUser } from '../types'
import IconFont from '../assets/icon'

const { Content } = Layout

const plugins = [
  gfm(),
  highlight()
  // Add more plugins here
]

interface Props {
  user: IUser
}

export const getServerSideProps: GetServerSideProps = async ctx => {
  const result = await userService.userInfo(ctx.req.cookies.token)
  if (result.stat === 'OK') {
    return {
      props: {
        user: result.data
      }
    }
  }
  return {
    redirect: {
      destination: '/login',
      permanent: false
    }
  }
}

export default function Post(props: Props) {
  const openBtn = React.useRef<HTMLInputElement>(null)
  const [value, setValue] = useState<string>('')
  const [title, setTitle] = useState<string>('')
  const [label, setLabel] = useState<string>('')
  const [banner, setBanner] = useState<string[]>([])

  const onclick = () => {
    openBtn.current?.click()
  }

  const onOpenChange = async () => {
    let file = openBtn.current?.files
    let keys: string[] = []
    for (let i = 0; i < file!.length; i++) {
      const res = await articleService.upload(file![i])
      keys.push(res.data)
    }
    setBanner(keys)
  }

  const postarticle = async () => {
    if (title === '' || label === '' || value === '') {
      toast('请填写完整')
    } else {
      await articleService.postArticle(title, value, label.split(' '), banner)
      setLabel('')
      setTitle('')
      setValue('')
      setBanner([])
      toast('发布成功')
    }
  }

  return (
    <div className={styles.div}>
      <Header user={props.user} />
      <div className={styles.title}>
        标题：
        <Input
          value={title}
          placeholder="title"
          onChange={e => {
            setTitle(e.target.value)
          }}
        />
      </div>
      <div className={styles.label}>
        文章标签(以空格隔开)：
        <Input
          value={label}
          placeholder="label1 label2..."
          onChange={e => {
            setLabel(e.target.value)
          }}
        />
      </div>

      <div className={styles.banner}>
        <div className={styles.input}>
          banner图(可选)：
          <div id="mask" className={styles.mask} onClick={onclick}>
            <IconFont type="icon-xiangji" className={styles.xiangji} />
          </div>
          <input
            ref={openBtn}
            id="input"
            type="file"
            multiple
            className={styles.none}
            onChange={onOpenChange}
          />
        </div>
        <div className={styles.current}>
          {banner.map((item, index) => {
            return (
              <div
                key={index}
                style={{
                  backgroundImage: `url(/api/article/download/${item})`,
                  width: '150px',
                  height: '150px',
                  backgroundSize: 'cover',
                  marginRight: '15px'
                }}
              ></div>
            )
          })}
        </div>
      </div>
      <Content style={{ margin: '20px 30px ', overflow: 'initial' }}>
        <Editor
          uploadImages={async files => {
            const key = await articleService.upload(files[0])
            return [
              {
                url: `/api/article/download/${key.data}`,
                alt: '' // optional
              }
            ]
          }}
          locale={zhHans}
          value={value}
          plugins={plugins}
          onChange={v => {
            setValue(v)
          }}
        />
      </Content>
      <Button className={styles.btn} onClick={postarticle}>
        发布文章
      </Button>
    </div>
  )
}
